package com.kinroy.briefreport.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kinroy.briefreport.dto.Result;
import com.kinroy.briefreport.dto.UserDto;
import com.kinroy.briefreport.entity.User;
import com.kinroy.briefreport.entity.UserInfo;
import com.kinroy.briefreport.enums.role.UserRole;
import com.kinroy.briefreport.mapper.UserMapper;
import com.kinroy.briefreport.service.IRegisterService;
import com.kinroy.briefreport.service.IUserService;
import com.kinroy.briefreport.utils.VerificationCodeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static  final  String REMIND_USERID_SET ="remindUserIds";

    //用户注册
    @Override
    @Transactional
    public Result register(UserDto userDto) {
        //1.先判断是否已经注册
        Boolean check = this.checkUserNameOrPhone(userDto);
        if (!check) {
            return Result.fail("注册失败！请重新填写注册信息！");
        }
        //2.使用shiro的md5加密方式加密
        String salt = VerificationCodeUtils.getCode(4, 1);
        String afterPassword = userDto.getPassword() + salt;
        String finalPassword = DigestUtils.md5DigestAsHex(afterPassword.getBytes());

        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setPassword(finalPassword);
        user.setSalt(salt);
        boolean save = userService.save(user);
        if (save) {
            //kinroy 2023.12.12 新增业务，完成注册后同时创建一下相关的userinfo存入
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getName, user.getName());
            User reslut = userService.getOne(wrapper);
            UserInfo userInfo = new UserInfo();
            /*设置默认值*/
            userInfo.setUserId(reslut.getUid());
            userInfo.setIntroduction("这个人很懒，什么都没留下");
            /*userInfo.setImage("null");*/
            //kinroy 2023.12.25新增设置用户默认头像
            userInfo.setAvatarImage("http://127.0.0.1:9000/briefreport/defaultAvatar.jpg");

            //kinroy 2024.1.27 新增业务，完成注册后向定时任务的用户id的Set中添加数据
            SetOperations<String, String> setOperations = redisTemplate.opsForSet();
            setOperations.add(REMIND_USERID_SET, String.valueOf( reslut.getUid()));


            try {
                userMapper.createUserInfo(userInfo);
                //kinroy 2023.12.25 默认设置一下新用户的权限role为员工
                userMapper.setUserRole(UserRole.STAFF.getCode(), reslut.getUid());
            } catch (Exception e) {
                e.printStackTrace();
                userService.removeById(reslut.getUid());
                return Result.fail("注册失败！请重新填写注册信息！");
            }
            return Result.ok("注册成功！");
        }
        return Result.fail("注册失败！请重新填写注册信息！");
    }

    /**
     * 使用手机登录，未注册的手机默认创建一个用户
     *
     * @return
     */
    @Override
    public Boolean fastRegister(String phoneNum) {
        //kinroy 2023.12.9 手机号快速注册报错，修复一下
        User user = new User();
        String salt = VerificationCodeUtils.getCode(4, 1);
        user.setSalt(salt);
        //设置初始名称(报错原因是用户名过长！注册的时候也要注意一下)
        user.setName("DefulUserName" + VerificationCodeUtils.getCode(4, 2));
        user.setPhone(phoneNum);
        //设置初始密码为 1234
        String password = "1234" + salt;
        String finalPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        user.setPassword(finalPassword);
        boolean save = false;
        try {
            save = userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            return save;
        }
        //kinroy 2023.12.12 新增业务，完成注册后同时创建一下相关的userinfo存入
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        User reslut = userService.getOne(wrapper);
        UserInfo userInfo = new UserInfo();
        /*设置默认值*/
        userInfo.setUserId(reslut.getUid());
        userInfo.setIntroduction("这个人很懒，什么都没留下");
        userInfo.setAvatarImage("http://127.0.0.1:9000/briefreport/defaultAvatar.jpg");

        //kinroy 2024.1.27 新增业务，完成注册后向定时任务的用户id的Set中添加数据
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        setOperations.add(REMIND_USERID_SET, String.valueOf( reslut.getUid()));

        //kinroy 2024.1.22 快速注册的用户没有存入对应信息导致其他模块获取总体用户报错，这里修复一下
        //设置权限默认值
        userMapper.setDefaultUserRole(reslut.getUid());

        try {
            Boolean userInfoSave = userMapper.createUserInfo(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            userService.removeById(reslut.getUid());
            return false;
        }
        return save;

    }

    /**
     * 校验用户名或密码是否已经注册
     *
     * @param userDto
     * @return true:表示可以注册   false：表示已经注册
     */
    @Override
    public Boolean checkUserNameOrPhone(UserDto userDto) {
        //当前端输入完成username或者phone时进行判断
        if ((userDto.getPhone() == null || userDto.getPhone().equals(""))
                && (userDto.getName() == null || userDto.getName().equals(""))) {
            //不能全部传入空的名称
            return false;
        }

        //修改了一下校验逻辑
        boolean phoneCheck = false;
        if (userDto.getPhone() != null) {
            if (!userDto.getPhone().equals("")) {
                LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(userDto.getPhone() != null && userDto.getPhone() != "", User::getPhone, userDto.getPhone());
                User one1 = userService.getOne(wrapper);
                if (one1 == null) {
                    phoneCheck = true;
                }
            }
        }
        boolean userNameCheck = false;
        if (userDto.getName() != null) {
            if (!userDto.getName().equals("")) {
                LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(userDto.getName() != null && userDto.getName() != "", User::getName, userDto.getName());
                User one2 = userService.getOne(wrapper);
                //一旦手机或者账号注册过了其中一个，即查出了数据，就返回false
                if (one2 == null) {
                    userNameCheck = true;
                }
            }
        }
        /*只要有一项是被注册过的都不能进行注册*/
        if (userNameCheck && phoneCheck) {
            return true;
        }
        return false;
    }


}
